package bgapi

import (
	"bgs/db"
	sqlc "bgs/db/sqlc"
	"bytes"
	"context"
	"encoding/json"
	"fmt"

	"github.com/nsqio/go-nsq"
	"go.uber.org/zap"
)

var (
	lastUserPvLogMessage *UserPvLogMessage = nil
)

// UserPvLogMessage UserPvLog message struct
type UserPvLogMessage struct {
	TS   int64 `json:"ts"`
	Data struct {
		// 冗余查询用
		BrandID int64 `json:"brand_id"`
		// 用户
		UserID int64 `json:"user_id"`
		// 分享用户
		ShareUserID int64  `json:"share_user_id"`
		Page        string `json:"page"`
	} `json:"data"`
}

// UserPvLogHandler UserPvLog message handler
type UserPvLogHandler struct {
	dao  *db.PgDao
	slog *zap.SugaredLogger
}

// NewUserPvLogHandler create a new handler for UserPvLog
func NewUserPvLogHandler(pgdao *db.PgDao, slog *zap.SugaredLogger) *UserPvLogHandler {
	return &UserPvLogHandler{
		dao:  pgdao,
		slog: slog.With("module", "UserPvLogHandler"),
	}
}

// HandleMessage implements the Handler interface.
func (h *UserPvLogHandler) HandleMessage(m *nsq.Message) error {
	if len(m.Body) == 0 {
		// Returning nil will automatically send a FIN command to NSQ to mark the message as processed.
		return nil
	}

	h.slog.Infof("message=>%s", string(m.Body))

	v := &UserPvLogMessage{}
	if decodeErr := json.NewDecoder(bytes.NewReader(m.Body)).Decode(v); decodeErr != nil {
		return fmt.Errorf("无法解析信息[UserFollowMessage]: %v", decodeErr)
	}
	if lastUserPvLogMessage != nil && lastUserPvLogMessage.TS >= v.TS {
		h.slog.Infof("过时的消息: lastUserPvLogMessage.TS:%v,v.TS:%v", lastUserPvLogMessage.TS, v.TS)
		return nil
	}

	ctx := context.Background()
	_, err := h.dao.Q.CreateUserPvLog(ctx, sqlc.CreateUserPvLogParams{
		UserID:      v.Data.UserID,
		BrandID:     sqlc.NInt64FromInt64(v.Data.BrandID),
		ShareUserID: sqlc.NInt64FromInt64(v.Data.ShareUserID),
		Page:        v.Data.Page,
	})

	if err != nil {
		return err
	}
	lastUserPvLogMessage = v
	// Returning a non-nil error will automatically send a REQ command to NSQ to re-queue the message.
	return nil
}
